package com.dex4d.ui.main.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.dex4d.R;
import com.dex4d.constants.IConstants;
import com.dex4d.core.AppToolBarBaseActivity;
import com.dex4d.core.http.DefaultTransformer;
import com.dex4d.core.http.JsonApiWrapper;
import com.dex4d.core.subscribers.ProgressSubscriber;
import com.dex4d.model.HttpResult;
import com.dex4d.model.RequestParam;
import com.dex4d.model.User;
import com.dex4d.ui.main.model.CoinToken;
import com.dex4d.ui.main.model.Dex4dTrade;
import com.dex4d.ui.main.model.TradeResult;
import com.dex4d.ui.main.view.bar.BubbleSeekBar;
import com.dex4d.utils.Arith;
import com.dex4d.utils.Commons;
import com.dex4d.utils.DecimalInputFilter;
import com.framework.bigdecimalutils.BigDecimalUtils;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import org.web3j.utils.Convert;
import org.web3j.utils.Numeric;

import java.math.BigInteger;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Collections;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by chengyuchun on 2018/11/26.
 */
public class WithdrawActivity extends AppToolBarBaseActivity {

    @BindView(R.id.btn_symbol)
    Button btn_symbol;

    @BindView(R.id.tv_available_withdraw)
    TextView tv_available_withdraw;

    @BindView(R.id.et_withdraw_amount)
    EditText et_withdraw_amount;

    @BindView(R.id.seek_bar)
    BubbleSeekBar seek_bar;

    @BindView(R.id.btn_withdraw)
    Button btn_withdraw;

    private ArrayList<CoinToken> mTokenList;
    private CoinToken mCoinToken;
    private String mGasFee;

    public static void start(Activity activity, ArrayList<CoinToken> tokenList) {
        Intent intent = new Intent(activity, WithdrawActivity.class);
        intent.putParcelableArrayListExtra(Commons.BUNDLE_KEYS.ALL_TRADE_TOKEN, tokenList);
        activity.startActivity(intent);
    }
    @Override
    protected void initToolbar() {
        showBackView();
        showTitle(getString(R.string.withdraw));
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_prepare_withdraw;
    }

    @Override
    protected void initVariables() {
        mTokenList = getIntent().getParcelableArrayListExtra(Commons.BUNDLE_KEYS.ALL_TRADE_TOKEN);
        if(mTokenList !=null && mTokenList.size()>0){
            mCoinToken = mTokenList.get(0);
            btn_symbol.setText(mCoinToken.getShowSymbol());
            tv_available_withdraw.setText(getString(R.string.available_withdraw_amount,mCoinToken.coins,mCoinToken.getShowSymbol()));
        }

        //监听输入
        et_withdraw_amount.setFilters(new InputFilter[] {new DecimalInputFilter()}); //小数点6位
        et_withdraw_amount.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if(s.length()>0 && !BigDecimalUtils.is(s.toString()).isNullOrZero()){
                    btn_withdraw.setBackgroundResource(R.drawable.btn_blue_clickable_bg);
                    btn_withdraw.setTextColor(getResources().getColor(R.color.white));
                    btn_withdraw.setClickable(true);
                }else {
                    btn_withdraw.setBackgroundResource(R.drawable.btn_blue_unclick_bg);
                    btn_withdraw.setTextColor(getResources().getColor(R.color.gray_B7C5CA));
                    btn_withdraw.setClickable(false);
                }
                calculateProgress(s.length()>0? s.toString():"0.0");
            }
        });

        seek_bar.setOnProgressChangedListener(new BubbleSeekBar.OnProgressChangedListenerAdapter() {
            @Override
            public void getProgressOnFinally(BubbleSeekBar bubbleSeekBar, int progress, float progressFloat, boolean fromUser) {
                super.getProgressOnFinally(bubbleSeekBar, progress, progressFloat, fromUser);
            }

            @Override
            public void getProgressOnActionUp(BubbleSeekBar bubbleSeekBar, int progress, float progressFloat) {
                super.getProgressOnActionUp(bubbleSeekBar, progress, progressFloat);
                calculateAmount(progress);
            }
        });

    }

    private void calculateProgress(final String inputAmount){
        String availableAmount = mCoinToken.coins;
        try {
            int progress  = (int)(Arith.div(Double.parseDouble(inputAmount),
                    Double.parseDouble(availableAmount),2) * 100);
            if(progress >= 100){
               seek_bar.setProgress(100);
            }else {
                seek_bar.setProgress((float) progress);
            }
        }catch (Exception e){

        }
    }

    private void calculateAmount(final int progress){
        String availableAmount = mCoinToken.coins;
        try{
            String withdrawAmount = Arith.mul(Double.parseDouble(availableAmount),
                    Arith.div(progress,100,2),6) + "";
            et_withdraw_amount.setText(withdrawAmount);
        }catch (Exception e){

        }
    }

    @Override
    protected void loadData() {

        final RequestParam gasParam = new RequestParam();
        gasParam.setId(1);
        gasParam.setJsonrpc(IConstants.JSON_RPC_VERSION);
        gasParam.setMethod(IConstants.CONTRACTSERVICE_GASPRICE);
        gasParam.setParams(Collections.singletonList(User.getInstance().getAddress()));
        //gas price
        JsonApiWrapper
                .serviceApi()
                .requestByParam(gasParam)
                .compose(new DefaultTransformer<HttpResult<String>>())  //取网络数据这个函数不能少，这是线程切换
                .subscribe(new ProgressSubscriber<HttpResult<String>>(this, false) {
                    @Override
                    public void onNext(HttpResult<String> result) {
                        //服务器传过来的 GasPrice 是十进制
                        BigInteger gasPrice =  new BigInteger(result.getResult());

                        BigInteger gasLimit = Numeric.toBigInt(Dex4dTrade.getHexGasLimit(TradeResult.FLAG_WITHDRAW));
                        mGasFee =  Convert.fromWei(gasPrice.multiply(gasLimit).toString(), Convert.Unit.ETHER).setScale(6, RoundingMode.CEILING).toString();
                    }
                });
    }

    @OnClick({R.id.btn_symbol,R.id.btn_withdraw})
    public void onViewClick(View view){
        switch (view.getId()){
            case R.id.btn_symbol:
                showPopWindow();
                break;
            case R.id.btn_withdraw:
                Bundle bundle = new Bundle();
                bundle.putInt(Commons.BUNDLE_KEYS.TRADE_TYPE,TradeResult.FLAG_WITHDRAW);
                bundle.putString(Commons.BUNDLE_KEYS.WITHDRAW_SYMBOL,mCoinToken.symbol);
                bundle.putString(Commons.BUNDLE_KEYS.COIN_AMOUNT,et_withdraw_amount.getText().toString()); //提现数量
                bundle.putString(Commons.BUNDLE_KEYS.GAS_CONSUMPTION,mGasFee);
                openActivity(TradeConfirmActivity.class,bundle);
        }

    }

    private void showPopWindow() {
        View rootView = findViewById(R.id.root_view); // 當前頁面的根佈局
        View contentView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.popupwindow, null);
        final PopupWindow popupWindow = new PopupWindow(contentView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT,true);

        RecyclerView rv_tokens = contentView.findViewById(R.id.rv_tokens);
        rv_tokens.setAdapter(new CommonAdapter<CoinToken>(this, R.layout.item_popupwindow, mTokenList) {
            @Override
            protected void convert(ViewHolder holder, final CoinToken coinToken, final int position) {
                holder.setText(R.id.tv_token_name, coinToken.getShowSymbol());
                holder.setOnClickListener(R.id.tv_token_name, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mCoinToken = coinToken;
                        btn_symbol.setText(mCoinToken.getShowSymbol());
                        et_withdraw_amount.setText("0");
                        tv_available_withdraw.setText(getString(R.string.available_withdraw_amount,mCoinToken.coins,mCoinToken.getShowSymbol()));
                        popupWindow.dismiss();
                    }
                });
            }
        });

        rv_tokens.setLayoutManager(new LinearLayoutManager(this));
        rv_tokens.addItemDecoration(new HorizontalDividerItemDecoration.Builder(this)
                .color(getResources().getColor(R.color.gray))
                .build());

        setBackgroundAlpha(0.3823f);//设置屏幕透明度
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                // popupWindow隐藏时恢复屏幕正常透明度
                setBackgroundAlpha(1.0f);
            }
        });
        popupWindow.showAtLocation(rootView, Gravity.BOTTOM | Gravity.CENTER, 0, 0);
    }

    /** * 设置添加屏幕的背景透明度 * */
    private void setBackgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgAlpha;
        getWindow().setAttributes(lp);
    }
}
